package com.android.kotlincoroutinemvvmdemo.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.android.kotlincoroutinemvvmdemo.R

/*
* 箭头view
* */
class ArrowView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : View(context, attributeSet) {

    private var mWidth = 0
    private var mHeight = 0

    private val mPaint0 by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            //拐角---(尖角)
            strokeJoin = Paint.Join.MITER
            strokeWidth = context.resources.getDimension(R.dimen.dp_2)
            color = context.resources.getColor(R.color.teal_700)
            style = Paint.Style.FILL
        }
    }

    private val mPath by lazy {
        Path()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        Log.d(TAG, "override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)")
        mWidth = when(MeasureSpec.getMode(widthMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                MeasureSpec.getSize(widthMeasureSpec)
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_60).toInt()
            }
        } - paddingStart - paddingEnd

        mHeight = when(MeasureSpec.getMode(heightMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                MeasureSpec.getSize(heightMeasureSpec)
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_60).toInt()
            }
        } - paddingTop - paddingBottom

        setMeasuredDimension(mWidth, mHeight)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        Log.d(TAG, "override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int)")
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        setBackgroundColor(context.resources.getColor(R.color.color_F3F3F3))
        canvas?.apply {
            val cx = mWidth / 2.0F
            val cy = mHeight / 2.0F
            translate(cx, cy)
            mPath.apply {
                moveTo(0F, -cy * 2 / 3)
                lineTo(-cx * 3 / 10, -cy / 3)
                lineTo(-cy / 10, -cy / 3)
                lineTo(-cy / 10, cy * 2 / 3)
                lineTo(cy / 10, cy * 2 / 3)
                lineTo(cx / 10, -cy / 3)
                lineTo(cx * 3 / 10, -cy / 3)
                close()
            }
            drawPath(mPath, mPaint0)
        }
    }

    companion object {
        const val TAG = "ArrowView"
    }
}